﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using RVEAd.Business;
using RVEAd.Business.Model;

namespace RVEAd.Forms
{
    public partial class FormDetaliiPlanDaily : Form
    {

        private RveBL rveBL;

        #region Properties

        public int SelectedMonth { get; set; }
        public int SelectedYear { get; set; }

        private DateTime currentDate;
        public DateTime CurrentDate
        {
            get
            {
                return currentDate;
            }

            set
            {
                if (value.DayOfWeek == DayOfWeek.Sunday)
                {
                    value = value.AddDays(1);
                }

                currentDate = value;
                dateTimeFilter.Value = value;

                LoadPlanData(value);
            }
        }


        #endregion

        #region Ctor
        public FormDetaliiPlanDaily()
        {
            InitializeComponent();
            this.Load += new EventHandler(FormDetaliiPlanDaily_Load);
        }
        #endregion

        private void LoadPlanData(DateTime data)
        {
            dataGridView1.DataSource = rveBL.GetAdPlans(data);
        }

        private AdPlanModel GetSelectedPlan()
        {
            if (dataGridView1.CurrentRow.DataBoundItem != null)
            {
                return (AdPlanModel)dataGridView1.CurrentRow.DataBoundItem;
            }

            return null;
        }

        private AdPlanModel GetSelectedPlan(int rowIndex)
        {
            if (dataGridView1.Rows[rowIndex].DataBoundItem != null)
            {
                return (AdPlanModel)dataGridView1.Rows[rowIndex].DataBoundItem;
            }

            return null;
        }

        #region Events handlers

        void FormDetaliiPlanDaily_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;

            rveBL = new RveBL();
            CurrentDate = new DateTime(SelectedYear, SelectedMonth, 1);

            // by default show summary for the first row
            var datasource = (List<AdPlanModel>)dataGridView1.DataSource;
            if (datasource != null && datasource.Count > 0)
            {
                dataGridView1.Rows[0].Selected = true;
                BuildLiveSummary();
            }
        }

        void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

        }

        void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > 2)
            {
                var cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;

                if (cell.Value != null)
                {
                    if (cell.Value.ToString().Equals("true", StringComparison.InvariantCultureIgnoreCase))
                    {
                        cell.Style.BackColor = Color.GreenYellow;
                    }
                    else if (cell.Value.ToString().Equals("false", StringComparison.InvariantCultureIgnoreCase))
                    {
                        cell.Style.BackColor = Color.White;
                    }

                    cell.Value = string.Empty;
                }

                //if (cell.Value != null && !string.IsNullOrEmpty(cell.Value.ToString().Trim()))
                //{
                //    cell.Style.BackColor = Color.GreenYellow;
                //}
                //else
                //{
                //    cell.Style.BackColor = Color.White;
                //}

                //cell.Value = string.Empty;
            }
        }

        void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            BuildLiveSummary();
        }

        void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.X && dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.ColumnIndex > 2)
            {
                int rowIndex = dataGridView1.CurrentCell.RowIndex;
                int columnIndex = dataGridView1.CurrentCell.ColumnIndex;

                if (dataGridView1.CurrentCell.Style.BackColor == Color.White || dataGridView1.CurrentCell.Style.BackColor.IsEmpty)
                {
                    dataGridView1.CurrentCell.Style.BackColor = Color.GreenYellow;
                    SetIntervalValue(rowIndex, columnIndex, true);
                }
                else
                {
                    dataGridView1.CurrentCell.Style.BackColor = Color.White;
                    SetIntervalValue(rowIndex, columnIndex, false);
                }
            }
        }



        private void SetIntervalValue(int rowIndex, int columnIndex, bool value)
        {
            var cell = dataGridView1.Rows[rowIndex].Cells[columnIndex].OwningColumn.Name;
            var selectedPlan = GetSelectedPlan(rowIndex);

            switch (cell)
            {
                case "AM1":
                    rveBL.SetIntervalInAdPlan(selectedPlan.AdPlanId, value, IntervalEnum.AM1);
                    break;

                case "AM2":
                    rveBL.SetIntervalInAdPlan(selectedPlan.AdPlanId, value, IntervalEnum.AM2);
                    break;

                case "AM3":
                    rveBL.SetIntervalInAdPlan(selectedPlan.AdPlanId, value, IntervalEnum.AM3);
                    break;

                case "PM1":
                    rveBL.SetIntervalInAdPlan(selectedPlan.AdPlanId, value, IntervalEnum.PM1);
                    break;

                case "PM2":
                    rveBL.SetIntervalInAdPlan(selectedPlan.AdPlanId, value, IntervalEnum.PM2);
                    break;
            }

            // not all summary
            var instantSummary = GetPlanSummary();

            int totalContract = int.Parse(instantSummary.PlanContract);
            int totalLuna = int.Parse(instantSummary.PlanMonth);

            if (totalLuna > totalContract)
            {
                MessageBox.Show("Ati depasit numarul programarilor din contract pentru luna curenta !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        void btnSave_Click(object sender, EventArgs e)
        {

        }
        void btnPrev_Click(object sender, EventArgs e)
        {
            DateTime nextDate = CurrentDate.AddDays(-1);

            if (nextDate.DayOfWeek == DayOfWeek.Sunday)
            {
                CurrentDate = nextDate.AddDays(-1);
            }
            else
            {
                CurrentDate = CurrentDate.AddDays(-1);
            }
        }
        void btnNex_Click(object sender, EventArgs e)
        {
            DateTime nextDate = CurrentDate.AddDays(1);

            if (nextDate.DayOfWeek == DayOfWeek.Sunday)
            {
                CurrentDate = nextDate.AddDays(1);
            }
            else
            {
                CurrentDate = CurrentDate.AddDays(1);
            }
        }

        void detaliiClientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var client = GetSelectedPlan();

            FormDetaliiPlanMonth frmMonthView = new FormDetaliiPlanMonth();
            frmMonthView.SelectedMonth = SelectedMonth;
            frmMonthView.SelectedYear = SelectedYear;
            frmMonthView.ClientAdId = client.CliendAdId;
            frmMonthView.ClientName = client.ClientName;

            frmMonthView.FormClosed += (oo, ee) =>
                {
                    LoadPlanData(CurrentDate);
                };

            frmMonthView.ShowDialog();
        }
        #endregion

        private Business.Model.DaySummaryModel GetPlanSummary()
        {
            AdPlanModel selectedPlan = GetSelectedPlan();
            DateTime selectedDate = dateTimeFilter.Value;

            return rveBL.GetPlanSummary(selectedPlan, selectedDate);
        }

        private Business.Model.DaySummaryModel BuildLiveSummary()
        {
            AdPlanModel selectedPlan = GetSelectedPlan();
            DateTime selectedDate = dateTimeFilter.Value;

            Business.Model.DaySummaryModel daySummaryModel = rveBL.GetLiveSummary(selectedPlan, selectedDate);
            dailyStatusControl1.SetData(daySummaryModel);

            // update grid interval columns
            // 2..6
            dataGridView1.Columns[3].HeaderText = string.Format("AM1 ({0})", daySummaryModel.PlanAM1);
            dataGridView1.Columns[4].HeaderText = string.Format("AM2 ({0})", daySummaryModel.PlanAM2);
            dataGridView1.Columns[5].HeaderText = string.Format("AM3 ({0})", daySummaryModel.PlanAM3);
            dataGridView1.Columns[6].HeaderText = string.Format("PM1 ({0})", daySummaryModel.PlanPM1);
            dataGridView1.Columns[7].HeaderText = string.Format("PM2 ({0})", daySummaryModel.PlanPM2);

            return daySummaryModel;
        }
    }

}
